package com.wanfajie.smsdistribute.db.helper

import android.database.sqlite.SQLiteDatabase
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper
import com.j256.ormlite.dao.Dao
import com.j256.ormlite.support.ConnectionSource
import com.j256.ormlite.table.TableUtils
import com.wanfajie.smsdistribute.MyApplication
import com.wanfajie.smsdistribute.config.PHONE_DB_NAME
import com.wanfajie.smsdistribute.config.PHONE_DB_VERSION
import com.wanfajie.smsdistribute.db.bean.phone.PhoneFieldValue
import com.wanfajie.smsdistribute.db.bean.phone.PhoneGroup
import com.wanfajie.smsdistribute.db.bean.phone.PhoneKeyField
import com.wanfajie.smsdistribute.db.bean.phone.PhoneNumber

object PhoneDatabaseHelper : OrmLiteSqliteOpenHelper(MyApplication.context, PHONE_DB_NAME, null, PHONE_DB_VERSION) {

    private val daoMap : HashMap<Class<*>?, Dao<*, *>?> = HashMap()

    override fun onCreate(database: SQLiteDatabase?, connectionSource: ConnectionSource?) {
        TableUtils.createTableIfNotExists(connectionSource, PhoneGroup::class.java)
        TableUtils.createTableIfNotExists(connectionSource, PhoneNumber::class.java)
        TableUtils.createTableIfNotExists(connectionSource, PhoneKeyField::class.java)
        TableUtils.createTableIfNotExists(connectionSource, PhoneFieldValue::class.java)
    }

    override fun onUpgrade(database: SQLiteDatabase?, connectionSource: ConnectionSource?, oldVersion: Int, newVersion: Int) {
    }

    override fun <D : Dao<T, *>?, T : Any?> getDao(clazz: Class<T>?): D {
        var dao: Dao<*, *>? = daoMap[clazz]
        if (dao == null) {
            dao = super.getDao<D, T>(clazz)
            daoMap[clazz] = dao
        }

        return dao as D
    }
}
